package com.example.demo.controller;

import com.example.demo.Response;
import com.example.demo.dto.ClothDTO;
import com.example.demo.dto.PostDTO;
import com.example.demo.service.FileService;
import com.example.demo.service.PostService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Set;

@RestController
public class PostController {
    @Autowired
    private PostService postService;
    @Autowired
    private FileService fileService;

    @GetMapping("post")
    public Response<List<PostDTO>> getAll(){
        return Response.newSuccess(postService.getAll());
    }
    @GetMapping ("post/{id}")
    public Response<PostDTO> getPostById(@PathVariable long id) {
        return Response.newSuccess(postService.getPostById(id));
    }
    @GetMapping ("post/userId/{userId}")
    public Response<Set<PostDTO>> getPostByUserId(@PathVariable long userId) {
        return Response.newSuccess(postService.getPostByUserId(userId));
    }
    @GetMapping ("post/title/{title}")
    public Response<Set<PostDTO>> getPostByTitle(@PathVariable String title) {
        return Response.newSuccess(postService.getPostByTitle(title));
    }
    @PutMapping ("post/{id}/{title}/{content}/{publicationDate}")
    public Response<PostDTO> updatePostByIdAndUserId(@PathVariable String title, @PathVariable String content, @PathVariable String publicationDate, @PathVariable long id, @PathVariable long userId, @PathVariable int likesCount, @PathVariable int commentsCount, @PathVariable int sharesCount, @PathVariable int favoritesCount) {
        return Response.newSuccess(postService.updatePostByIdAndUserId(title, content, publicationDate,id,userId,likesCount,commentsCount,sharesCount,favoritesCount));
    }
    @PostMapping ("post/{userId}")
    public Response<Long> addNewPostByUserId(@RequestParam("postDTO") String postDTOJson,@PathVariable long userId,@RequestParam(value = "imageFile", required = false) MultipartFile imageFile) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            PostDTO postDTO = objectMapper.readValue(postDTOJson, PostDTO.class);
            if (imageFile != null) {
                String imageName = fileService.storeFile(imageFile);
                postDTO.setImageName(imageName);
            }
            long postId = postService.addNewPostByUserId(postDTO, userId);
            return Response.newSuccess(postId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @DeleteMapping("post/id")
    public void deletePostById(@RequestParam long id) {
        postService.deletePostById(id);
    }
}
